package com.dreamstations.changshads.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.dreamstations.changshads.R;
import com.dreamstations.changshads.activity.ArticleDetailActivity;
import com.dreamstations.changshads.activity.ArticleDetail_WebActivity;
import com.dreamstations.changshads.adapter.DSRvAdapter;
import com.dreamstations.changshads.entity.BaseBean;
import com.dreamstations.changshads.util.DSRequest;
import com.dreamstations.changshads.util.DSUtils;
import com.dreamstations.changshads.util.L;
import com.zhy.base.adapter.ViewHolder;
import com.zhy.base.adapter.recyclerview.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 用来测试的
 */
public abstract class BaseFragmentForHome<T> extends Fragment {
    private static final String TAG = BaseFragmentForHome.class.getName();
    public static final String PARAM_TYPEID = "typeId";//添加静态常量
    public static final String PARAM_PAGE = "page";
    protected boolean isFirstIn = true;
    private int tryAgainTime;
    /**
     * 上层设置type和category并加Tag
     * 在这里的每一个必须手动设置cacheType和page参数
     */
    private DSRequest dsRequest;
    private int currentPage = 1;
    private Object requestTag;

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private Handler mHandler;

    private DSRvAdapter<T> adapter;
    private DSRvAdapter.RvSupport header, footer;
    private DSRvAdapter.RvSupport<T> item;
    private OnItemClickListener<T> onItemClickListener;
    private boolean enablePullLoadMore = false;
    private LinearLayoutManager layoutManager;

    private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        int lastVisibleItem = 0;

        @Override
        public void onScrollStateChanged(final RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
                adapter.setFooter_state(adapter.FOOTER_STATE_REFRESHING);
                dsRequest
                        .addParams("page", String.valueOf(++currentPage))
                        .cacheType(DSUtils.NETWORK_ELSE_CACHED)
                        .build()
                        .execute(new DSRequest.DSCallback<List<T>>() {
                            @Override
                            public void onResponse(List<T> result) {
                                if (adapter == null) return;
                                adapter.addMoreItemData(result);
                                adapter.setFooter_state(adapter.FOOTER_STATE_PENDING);
                                L.i(TAG, "上拉加载成功");
                            }

                            @Override
                            public void onFailure(String msg) {
//                                        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
                                if (adapter == null) return;
                                if (currentPage > 1) {
                                    recyclerView.clearOnScrollListeners();
                                    adapter.removeFooter();
                                }
                            }
                        });
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            lastVisibleItem = layoutManager.findLastVisibleItemPosition();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler();

        //初始化各个必要的组件
        dsRequest = getDsRequest();
        requestTag = dsRequest.getTag();
        if (requestTag == null) throw new RuntimeException("没有设置Tag！");
        item = getItem();
        header = getHeader();
        enablePullLoadMore = getEnablePullLoadMore();
        onItemClickListener = getOnItemClickListener();
    }

    public abstract
    @NonNull
    DSRequest getDsRequest();

    @NonNull
    public abstract DSRvAdapter.RvSupport<T> getItem();

    public abstract OnItemClickListener getOnItemClickListener();

    public abstract DSRvAdapter.RvSupport getHeader();

    public abstract boolean getEnablePullLoadMore();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        swipeRefreshLayout = (SwipeRefreshLayout) inflater.inflate(R.layout.simple_refreshable, container, false);
        recyclerView = (RecyclerView) swipeRefreshLayout.getChildAt(1);

        initView();

        int cacheType=DSUtils.NETWORK_ELSE_CACHED;
        if (isFirstIn){
            cacheType=DSUtils.ONLY_CACHED;
        }
        loadData(1, cacheType);

        return swipeRefreshLayout;
    }

    /**
     * 加载数据到item
     *
     * @param page      页码
     * @param cacheType CACHE还是NETWORK
     */
    private void loadData(int page, int cacheType) {
        DSUtils.getInstance().cancelByTag(requestTag);
        swipeRefreshLayout.setRefreshing(true);
        dsRequest
                .addParams("page", String.valueOf(page))
                .cacheType(cacheType)
                .build()
                .execute(new DSRequest.DSCallback<List<T>>() {
                    @Override
                    public void onResponse(List<T> result) {
                        if (adapter == null) return;
                        tryAgainTime = 0;
                        adapter.setItemDatas(result);
                        if (swipeRefreshLayout.isRefreshing()) {
                            swipeRefreshLayout.setRefreshing(false);
                        }
                        if (isFirstIn) {
                            isFirstIn = false;
                            loadData(1, DSUtils.NETWORK_ELSE_CACHED);
                        }
                        if (enablePullLoadMore && result.size() > 8) {
                            adapter.setFooter(footer);
                            recyclerView.clearOnScrollListeners();
                            recyclerView.addOnScrollListener(onScrollListener);
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
//                        Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                        Log.w(TAG, "=>loadData:" + msg);
                        if (swipeRefreshLayout.isRefreshing()) {
                            swipeRefreshLayout.setRefreshing(false);
                        }
                        if (tryAgainTime < 8) {
                            loadData(1, DSUtils.NETWORK_ELSE_CACHED);
                            tryAgainTime++;
                            L.w(TAG, "=>loadData:tryAgain:" + tryAgainTime);
                        }
                    }
                });

    }


    private void initView() {
        //设置布局管理器
        layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        //设置item间隔
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(0, 0, 0, 16);
            }
        });


        adapter = new DSRvAdapter<T>(getContext(), new ArrayList<T>()
                , item);
        recyclerView.setAdapter(adapter);
        adapter.setHeader(header);

        //启用上拉加载功能
//        if (enablePullLoadMore) {
            footer = new DSRvAdapter.RvSupport() {
                @Override
                public int getItemViewType(Object data) {
                    return 0;
                }

                @Override
                public ViewHolder createHolder(Context context, ViewGroup parent, int viewType) {
                    return ViewHolder.get(context, null, parent, R.layout.simple_refreshing, -1);
                }

                @Override
                public void convert(ViewHolder holder, Object data) {
//                    if ((int) data == DSRvAdapter.FOOTER_STATE_PENDING)
//                        holder.setText(R.id.refreshing_text, "上拉加载更多...");
//                    else
//                        holder.setText(R.id.refreshing_text, "正在加载...");

                }

            };
//            recyclerView.addOnScrollListener(onScrollListener);
////            adapter.setFooter(footer);
//        }
//        adapter.setOnItemClickListener(onItemClickListener);
        adapter.setOnItemClickListener(new OnItemClickListener<BaseBean>() {
            @Override
            public void onItemClick(ViewGroup parent, View view, BaseBean data, int position) {
                Intent intent = new Intent();
                if (data.getTemplate() == 1) {
                    intent.setClass(getActivity(), ArticleDetail_WebActivity.class);
                } else {
                    intent.setClass(getActivity(), ArticleDetailActivity.class);
                }
                intent.putExtra("data", data);
                startActivity(intent);
            }

            @Override
            public boolean onItemLongClick(ViewGroup parent, View view, BaseBean o, int position) {
                return false;
            }
        });

//        设置刷新监听
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                L.i(TAG, "=>onRefresh");
                currentPage = 1;
                loadData(currentPage, DSUtils.NETWORK_ELSE_CACHED);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
//        int cacheType=DSUtils.NETWORK_ELSE_CACHED;
//        if (isFirstIn){
//            cacheType=DSUtils.ONLY_CACHED;
//        }
//        loadData(1, cacheType);
    }

    @Override
    public void onPause() {
        DSUtils.getInstance().cancelByTag(requestTag);
        super.onPause();
    }
}
